import Koa from 'koa';
var app = new Koa()
//require('babel-core/register');
const views = require('koa-views');
const bodyparser=require('koa-bodyparser')
const wechatdate = require("./middleware/wechatdate.js");
app.use(wechatdate())
const path = require('path')
const statics = require('koa-static')
const Router = require('koa-router')
const db = require("./model/db.js");

app.use(bodyparser({
  "formLimit" : "5mb",
  "jsonLimit":"5mb",
  "textLimit":"5mb"
}));

const common = require('./common');

const index = require('./router/router');
const kefu = require('./router/kefu');
const list = require('./router/list');
const reg = require('./router/reg');
const login = require('./router/login');
const uploadheader = require('./router/uploadheader');

const wechat = require('./router/wechat');

const blog = require('./router/blog');
//session公式：
var session = require('koa-session');
app.keys = ['some secret hurr'];
const CONFIG = {
  key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
  maxAge: 8640000, /** (number) maxAge in ms (default is 1 days) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
};
app.use(session(CONFIG, app))

const staticPath = './public'

app.use(statics(
  path.join(__dirname, staticPath)
))


//ejs engine
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}));


//聊天室
const router = new Router()
router.use('/', index.routes(), index.allowedMethods());
router.use('/kefu', kefu.routes(), kefu.allowedMethods());
router.use('/list', list.routes(), list.allowedMethods());
router.use('/reg', reg.routes(), reg.allowedMethods());
router.use('/login', login.routes(), login.allowedMethods());
router.use('/uploadheader', uploadheader.routes(), uploadheader.allowedMethods());


router.use('/wechat',wechat.routes(),wechat.allowedMethods())


router.use('/blog', blog.routes(), blog.allowedMethods());
app.use(router.routes()).use(router.allowedMethods())

// support socket.io
const server = require('http').Server(app.callback());
const io = require('socket.io')(server);




io.set('heartbeat interval', 60000);
io.set('heartbeat timeout', 5000);
io.on('connection', function (socket) {
  //连接成功后, 用户登陆
  socket.on('login', common.addUser);

  //连接断开
  socket.on('disconnect', common.removeUser);

  //收到客户发来的消息
  socket.on('new message', common.onMessage);

  socket.on('error', common.onError);
});



server.listen(3001)

